<template>
    <div class="loginWarp">
        <div class="loginBox">
            <h2>小U商城后台管理系统</h2>
            <el-form ref="ruleFormRef" :model="loginForm" :rules="rules" label-width="120px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="loginForm.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="loginForm.password" type="password" />
                </el-form-item>
                <!-- <el-form-item> -->
                <el-button type="primary" @click="sub(ruleFormRef)">
                    登录
                </el-button>
                <!-- </el-form-item> -->
            </el-form>
        </div>
    </div>
</template>
<script lang="ts" setup>
// setup中  import必须放在首行
// setup中没有this
// reactive 创建响应式的数据对象  reactive({})
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router'
import { userlogin } from '../request/api'
import { useStore } from 'vuex';

// 调用仓库
let store = useStore();
const loginForm = ref({
    username: '',
    password: ''
})
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 6, message: '长度在2-6位字符', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '长度在6-16位字符', trigger: 'blur' },
    ],

})
// 声明ref
let ruleFormRef = ref<FormInstance>();
//设定路由控制器的方法
let router = useRouter()
const sub = async (formEL: undefined | FormInstance) => {
    if (!formEL) return;
    await formEL.validate(val => {
        if (val) {
            userlogin(loginForm.value).then(res => {
                if (res.code == 200) {
                    // 登录成功
                    ElMessage.success(res.msg);
                    // 将登陆信息存储在仓库
                    store.commit('USER_INFO',res.list)
                    // 跳转首页
                    router.push('/index');
                } else {
                    // 登录失败
                    ElMessage.error(res.msg);
                }
            })

        }
    })

}

// 点击回车也可以进行登录
const keyDown = (e: any) => {
    if (e.keyCode == 13) {
        // window.addEventListener('login', this.sub)
        sub(ruleFormRef.value);

    }
}
window.addEventListener('keydown', keyDown)










</script>
<style scoped lang="less">
h2 {
    margin: 0 0 20px 30px;
}

.loginWarp {
    width: 100vm;
    height: 100vh;
    // width: 100%;
    // height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

}

.loginBox {
    width: 500px;
    height: 300px;
    // border: 1px solid red;
    text-align: center;
    // background-color: bisque; 
}

.el-button {
    margin-left: 0;
}
</style>